package com.bicon.botu.mall.goods.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bicon.botu.commons.constants.MallConstants;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.entity.*;
import com.bicon.botu.mall.goods.service.*;
import com.bicon.botu.mall.goods.vo.DrugPriceVo;
import com.bicon.botu.mall.goods.vo.ProductListVo;
import com.bicon.botu.mall.goods.vo.TranceVo;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.BeanMapper;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import com.bicon.botu.core.base.repository.redis.RedisTemplateUtil;
import com.bicon.botu.mall.goods.vo.ProductVo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 商品控制器
 * </p>
 *
 * @author 孙永刚
 * @since 2017-07-19
 */
@RestController
@RequestMapping("/V1.0.0/product")
public class ProductController extends BaseController {

    @Autowired

    private IProductService productService;

    @Autowired

    private IProductRepertoryService productRepertoryService;


    @Autowired

    private IProductPictureService iProductPictrueService;


    @Autowired
    private IClassAttributeService classAttributeService;

    @Autowired
    private IProductPictureService pictrueService;

    @Autowired
    private IProductRepertoryService repertoryService;

    @Autowired
    private ITraceElementService elementService;

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    IProductCommentService iProductCommentService;
    /**
     * 添加商品
     *
     * @param productType   商品类型 非定制  定制
     * @param classfily     分类Id
     * @param brandId       品牌Id
     * @param supplier      供货商
     * @param buyingPrice   进货价
     * @param productName   商品名
     * @param description   描述
     * @param lable         标签
     * @param details       详细描述
     * @param weight        重量
     * @param noticeNum     警告数量
     * @param upShelves     是否上架
     * @param isProduct     是否作为商品
     * @param isFreeFreight 是否免运费
     * @param logisticsType 物流商
     * @param productAttr   产品skujson
     * @param productRegion 产品销售区域
     * @param isOnBefore    是否启用前身文字
     * @param isOnAfter     是否启用后身文字定义
     * @param beforeText    前身文字
     * @param afterText     后身文字
     * @param traceElement  是否启用微量元素自定义
     * @param element       微量元素json
     * @param saveOrUpdate  操作类型
     * @param productId     商品Id
     * @param productCode   商品编号
     * @return
     */
    @RequestMapping(value = "/insertOrUpdateProduct", method = RequestMethod.POST)
    public BaseResult insertOrUpdateProduct(@RequestParam("productType") String productType, @RequestParam("classfily") String classfily,
                                            @RequestParam("brandId") String brandId, @RequestParam(value = "supplier", required = false) String supplier,
                                            @RequestParam("buyingPrice") BigDecimal buyingPrice, @RequestParam("productName") String productName,
                                            @RequestParam(value = "description", required = false) String description, @RequestParam("lable") String lable,
                                            @RequestParam("details") String details, @RequestParam(value = "weight", required = false) Double weight,
                                            @RequestParam("noticeNum") Integer noticeNum, @RequestParam("upShelves") String upShelves,
                                            @RequestParam("isProduct") String isProduct, @RequestParam("isFreeFreight") String isFreeFreight, @RequestParam("logisticsType") String logisticsType,
                                            @RequestParam(value = "productAttr", required = false) String productAttr, @RequestParam(value = "productRegion", required = false) String productRegion,
                                            @RequestParam(value = "isOnBefore", required = false) String isOnBefore, @RequestParam(value = "isOnAfter", required = false) String isOnAfter,
                                            @RequestParam(value = "beforeText", required = false) Integer beforeText, @RequestParam(value = "afterText", required = false) Integer afterText,
                                            @RequestParam(value = "traceElement", required = false) String traceElement, @RequestParam(value = "element", required = false) String element,
                                            @RequestParam(value = "saveOrUpdate", required = false) String saveOrUpdate, @RequestParam(value = "productId", required = false) String productId,
                                            @RequestParam(value = "productCode") String productCode, @RequestParam("pictureStr") String pictureStr) {
        int result = productService.selectCount(new EntityWrapper<Product>().eq("product_code", productCode));

        //判断商品编号是否存在
        if (result > 0 && StringUtils.isEmpty(productId)) {
            return sendResult(GoodsConstants.RESPONSE_CODE_601, GoodsConstants.RESPONSE_MESSAGE_601);
        }
        //添加商品信息
        Boolean resultAdd = productService.addProductInfo(classfily, description, isFreeFreight, isProduct, lable, logisticsType, noticeNum, productName, productType, upShelves, supplier, weight, details, brandId, productRegion,
                isOnBefore, isOnAfter, beforeText, afterText, traceElement, saveOrUpdate, productId, productAttr, element, productCode, buyingPrice, pictureStr);
        if (resultAdd) {
            return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200);
        }
        return sendResult(GoodsConstants.RESPONSE_CODE_600, GoodsConstants.RESPONSE_MESSAGE_600);
    }


    /**
     * 商品列表/回收站商品列表
     *
     * @param upShelves   上架状态
     * @param classFliy   分类
     * @param productName 商品名
     * @param productType 商品类型  0 非定制  1 定制
     * @param pageSize    每页条数
     * @param pageNo      页码
     * @param logicDelete 0  商品列表  1 商品回收站
     * @return
     */
    @RequestMapping("/list")
    public BaseResult getProductList(@RequestParam(value = "upShelves", required = false) String upShelves,
                                     @RequestParam(value = "classFliy", required = false) String classFliy,
                                     @RequestParam(value = "productName", required = false) String productName,
                                     @RequestParam(value = "productType", required = false) String productType,
                                     @RequestParam(value = "logicDelete") String logicDelete,
                                     @RequestParam(value = "brandId", required = false) String brandId,
                                     @RequestParam("pageSize") int pageSize, @RequestParam("pageNo") int pageNo) {
        EntityWrapper<Product> wrapper = new EntityWrapper<>();
        // wrapper.setEntity(Product);
        //查询商品列表时 logicDelete=0 查询商品回收站时 logicDelete=1
        wrapper.eq("logic_delete", logicDelete);
        if (!StringUtils.isEmpty(upShelves)) {
            wrapper.and().eq("up_shelves", upShelves);
        }
        if (!StringUtils.isEmpty(classFliy)) {
            wrapper.and().like("category_id", classFliy);
        }
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.and().eq("brand_id", brandId);
        }
        if (!StringUtils.isEmpty(productName)) {
            wrapper.like("product_name", "%" + productName + "%");
        }
        if (!StringUtils.isEmpty(productType)) {
            wrapper.and().eq("product_type", productType);
        }
        wrapper.orderBy("create_date", false);
        Page page = productService.selectPage(new Page<Product>(pageNo, pageSize), wrapper);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, page);
    }


    /**
     * 批量操作商品状态  上架 下架 删除 还原  物理删除
     *
     * @param operation 操作  0 批量上架 1.批量下架  2.批量删除逻辑 3.批量商品状态还原 4.商品批量删除物理
     * @param ids       id ..,..,...
     * @return
     */
    @RequestMapping("/batchOperation")
    public BaseResult batchOperation(@RequestParam("operation") String operation, @RequestParam("ids") String ids) {
        // EntityWrapper<Product> wrapper = new EntityWrapper<>();
        // 0 批量上架 1.批量下架  2.批量删除逻辑 3.批量商品状态还原 4.商品批量删除物理
        boolean result = false;
        String[] id = ids.split(",");
        List<Product> list = new ArrayList<>();
        List<String> stringList = new ArrayList<>();
        for (String stringId : id) {
            Product product = new Product();
            if (operation.equals(GoodsConstants.PRODUCT_UP_SHELVES)) {
                //批量上架
                product.setUpShelves(GoodsConstants.PRODUCT_UP_SHELVES);
            } else if (operation.equals(GoodsConstants.PRODUCT_DOWN_SHELVES)) {
                //批量下架
                if (productService.searCarefullyGoods("%" + stringId + "%") > 0) {
                    return sendResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
                }
                product.setUpShelves(GoodsConstants.PRODUCT_DOWN_SHELVES);
            } else if (operation.equals(GoodsConstants.PRODUCT_BATCH_DELETE)) {
                //批量删除
                if (productService.searCarefullyGoods("%" + stringId + "%") > 0) {
                    return sendResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
                }
                product.setLogicDelete(GoodsConstants.DEL_LOGIC_DELETE);
                product.preUpdate();
            } else if (operation.equals(GoodsConstants.PRODUCT_BATCH_UPDATE)) {
                //批量还原
                product.setLogicDelete(GoodsConstants.DEL_LOGIC_NORMAL);
            }/*else if(operation.equals(GoodsConstants.PRODUCT_BATCH_REALLY_DELETE)){

            }*/
            product.setId(stringId);
            list.add(product);
            stringList.add(stringId);
            if (operation.equals(GoodsConstants.PRODUCT_BATCH_REALLY_DELETE)) {
                Map map = new HashMap();
                map.put("product_id", stringId);
                result = productRepertoryService.deleteByMap(map);
            }
        }
        if (operation.equals(GoodsConstants.PRODUCT_BATCH_REALLY_DELETE)) {
            result = productService.deleteBatchIds(stringList);
        } else {
            result = productService.updateBatchById(list);
        }
        //查询频道表中是否有将要删除和下架的商品
        if (operation.equals(GoodsConstants.PRODUCT_DOWN_SHELVES)) {
            //批量下架
            if (productService.searchChannelGoods(stringList) > 0) {
                return sendResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
            }
        } else if (operation.equals(GoodsConstants.PRODUCT_BATCH_DELETE)) {
            //批量删除
            if (productService.searchChannelGoods(stringList) > 0) {
                return sendResult(MallConstants.RESPONSE_CODE_604, MallConstants.RESPONSE_MESSAGE_604);
            }
        }
        if (result) {
            productService.batchOpertion(ids, operation);
            return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200);
        }
        return sendResult(GoodsConstants.RESPONSE_CODE_600, GoodsConstants.RESPONSE_MESSAGE_600);

    }

    /**
     * 获取商品详情
     *
     * @param productId 商品Id
     * @return
     */
    @RequestMapping("/getProductInfo")
    public BaseResult getProductInfo(@RequestParam("productId") String productId) {
        //查询商品信息
        Product product = productService.selectOne(new EntityWrapper<Product>().eq("id", productId));
        //查询产品信息
        List<ProductRepertory> repertoryList = productRepertoryService.selectList(new EntityWrapper<ProductRepertory>().eq("product_id", productId).eq("logic_delete", GoodsConstants.DEL_LOGIC_NORMAL).orderBy("create_date", true));
        String newPath = product.getCategoryId().substring(product.getCategoryId().lastIndexOf("#") + 1);
        ClassAttribute attribute = classAttributeService.selectOne(new EntityWrapper<ClassAttribute>().eq("class_id", newPath));
        Set<String> set = new HashSet();
        Set<String> set1 = new HashSet();
        List list = new ArrayList();
        List list1 = new ArrayList();
        Map map = new HashMap();
        for (ProductRepertory rr : repertoryList) {
            // String str=  rr.getProductArrId1();
            set.add(rr.getProductArrId1());
            set1.add(rr.getProductArrId2());
        }
        for (String str : set) {
            ClassAttributeItem item = new ClassAttributeItem().selectById(str);
            list.add(item);
        }
        for (String str : set1) {
            ClassAttributeItem item = new ClassAttributeItem().selectById(str);
            list1.add(item);
        }
        //查询商品图片
        List<ProductPicture> pictrueList = iProductPictrueService.selectList(new EntityWrapper<ProductPicture>().eq("product_id", productId).orderBy("is_main", false));


        //查询微量元素
        if (product.getProductType().equals(GoodsConstants.CUSTOM_STATE1)) {
            List<TraceElement> elementList = elementService.selectList(new EntityWrapper<TraceElement>().eq("product_id", productId));
            Collections.sort(elementList);
            //微量元素
            map.put("TraceElement", elementList);

        }
        map.put("attribute", attribute);
        map.put("attr", list);
        map.put("attr1", list1);
        //商品信息
        map.put("product", product);
        //产品库存信息
        map.put("repertoryList", repertoryList);
        //图片
        map.put("pictrueList", pictrueList);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, map);

    }

    /**
     * 根据Id删除微量元素
     *
     * @param id
     * @param productId
     * @return
     */
    @RequestMapping("deleByElementId")
    public BaseResult deleByElementId(@RequestParam("id") String id, @RequestParam("productId") String productId) {
        boolean result = new TraceElement().deleteById(id);
        List<TraceElement> list = new ArrayList<>();
        if (result) {
            list = new TraceElement().selectList(new EntityWrapper().eq("product_id", productId));
        }
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, list);
    }

    /**
     * 获取最近使用类目
     *
     * @return
     */
    @RequestMapping("getClassName")
    public BaseResult getClassName() {
        Product product = new Product().selectOne(new EntityWrapper().orderBy("create_date", false).isNotNull("category_id").last("limit 1"));
        StringBuffer buffer = new StringBuffer();

        if (null != product) {
            String[] ss = product.getCategoryId().split("#");
            for (String s : ss) {
                if (!"1".equals(s) && !"".equals(s)) {
                    Classfication fication = new Classfication().selectById(s);
                    buffer.append(fication.getName()).append("-");
                }
            }
        }
        String string = buffer.substring(0, buffer.toString().length());
        Map<String, String> map = new HashedMap();
        map.put("classesName", string);
        map.put("classesId", product.getCategoryId());
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, map);
    }


    /**
     * 修改商品是否展示状态
     *
     * @param productIdsJson
     * @param state
     */
    @RequestMapping("updateProductState")
    public BaseResult updateProductState(@RequestParam("productIdsJson") String productIdsJson, @RequestParam("state") String state) {
        List<Product> list = new ArrayList<>();
        // List<String> strings = JSONArray.parseArray(productIdsJson, String.class);
        String[] strings = productIdsJson.split(",");
        if (strings.length > 0) {
            for (String productId : strings) {
                Product product = new Product();
                product.setId(productId);
                product.setShowState(state);
                list.add(product);
            }
            boolean result = productService.updateBatchById(list);
            if (result) {
                return sendResult200();
            }
            return sendResult(GoodsConstants.RESPONSE_CODE_600, GoodsConstants.RESPONSE_MESSAGE_600);
        }
        return sendResult400();
    }

    /**
     * 根据商品名称查询列表(医疗)
     *
     * @param productName
     * @return
     */
    @RequestMapping(value = "/findByProductName", method = RequestMethod.POST)
    public BaseResult findByProductName(@RequestParam(required = false) String productName) {
        List<DrugPriceVo> drugPriceVoList = productService.findByProductName(productName);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, drugPriceVoList);
    }

    /**
     * 商品列表查询
     *
     * @param pageSize 显示条数
     * @param pageNo   当前页码
     * @return
     */
    @RequestMapping("getProductList")
    public BaseResult getProductList(@RequestParam(value = "ids", required = false) String ids,
                                     @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNo") Integer pageNo
    ) {
        Map<String, Object> map = new HashMap<>();
        Page page = new Page(pageNo, pageSize);
        if (!org.springframework.util.StringUtils.isEmpty(ids)) {
            map.put("ids", ids.split(","));
        }
        Page<ProductListVo> listVoPage = productService.getProductList(page, map);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, listVoPage);
    }

    /**
     * 商品上下架统计
     * @return
     */
    @RequestMapping("shelvesTotal")
    public BaseResult shelvesTotal(){
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, this.productService.goodsStatistic());
    }

    /**
     * 查询商品详细信息
     *
     * @param productId
     * @return
     */
    @RequestMapping("getProductInfoForH5")
    public BaseResult getProductInfoForH5(@RequestParam("productId") String productId) {

        Map<String, Object> map = new HashedMap();
        //查询商品信息
        Product product = productService.selectById(productId);
        //查询商品图片
        List<ProductPicture> pictrueList = pictrueService.selectList(new EntityWrapper<ProductPicture>().eq("product_id", productId));
        //查询商品详细信息
        List<ProductRepertory> repertoryList = repertoryService.selectList(new EntityWrapper<ProductRepertory>().eq("product_id", productId).eq("logic_delete", GoodsConstants.DEL_LOGIC_NORMAL));
        //如果该商品是定制商品
        if (null == product) {
            return sendResult(GoodsConstants.RESPONSE_CODE_602, GoodsConstants.RESPONSE_MESSAGE_602);
        }
        if (product.getProductType().equals(GoodsConstants.CUSTOM_STATE1)) {
            map.put("productTrance", GoodsConstants.CUSTOM_STATE1);
            //查询该用户是否已完成定制
            TranceVo vo = new TranceVo();
        } else {
            map.put("productTrance", GoodsConstants.CUSTOM_STATE2);
        }
        //如果不是免运费商品
        if ("2".equals(product.getIsFreeFreight())) {
            map.put("logistics", productService.selectLogisticsCenter(productId));
        }
        String address = redisHandler.getGlobalRedisTemplate().getHash(GoodsConstants.H5, "", GoodsConstants.H5_KEY);
        map.put("product", product);
        map.put("pictureList", pictrueList);
        map.put("repertoryList", repertoryList);
        map.put("h5Url", address + productId);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, map);
    }


    /**
     * 初始化商品信息到redis
     */
    @RequestMapping(value = "innitProductInfo", method = RequestMethod.POST)
    public BaseResult innitProductInfo() {
        List<Product> list = new Product().selectAll();
        List<ProductVo> listVo = BeanMapper.mapList(list, ProductVo.class);
        RedisTemplateUtil redisTemplateUtil = redisHandler.getLocalRedisTemplate();
        for (ProductVo productVo : listVo) {
            ProductPicture pictrue = new ProductPicture().selectOne(new EntityWrapper().eq("product_id", productVo.getId()).eq("is_main", "1"));
            if (null != pictrue) {
                productVo.setPicture(pictrue.getProductUrl());
            }
            redisTemplateUtil.cacheStringValue(GoodsConstants.PRODUCT_INFO, productVo.getId(), JSONObject.toJSONString(productVo));
        }
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200);
    }

    /**
     * 初始化商品信息到redis
     */
    @RequestMapping(value = "innitCustomWater", method = RequestMethod.POST)
    public BaseResult innitCustomWater(@RequestParam String id, @RequestParam String pictureId) {
        Product product = new Product().selectById(id);
        ProductPicture productPicture = new ProductPicture().selectById(pictureId);
        RedisTemplateUtil redisTemplateUtil = redisHandler.getLocalRedisTemplate();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", product.getProductName());
        jsonObject.put("combinationName", product.getLable());
        jsonObject.put("itemImage", productPicture.getProductUrl());
        jsonObject.put("combinationId", product.getId());
        redisTemplateUtil.cacheStringValue(GoodsConstants.BIKANG_DINGZHI_WATER, id, jsonObject.toJSONString());
        redisTemplateUtil.cacheStringValue(GoodsConstants.BIKANG_DINGZHI_WATER, "id", id);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200);

    }


    /**
     * 商品销量TOP10
     * @return
     */
    @RequestMapping(value = "salesVolumeTop10", method = RequestMethod.GET)
    public BaseResult salesVolumeTop10(@RequestParam(value = "type") Integer type,@RequestParam(value = "startTime",required = false) String startTime, @RequestParam(value = "endTime",required = false) String endTime){
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, repertoryService.salesVolumeTop10(type,startTime,endTime));
    }


}
